package com.ruoyi.business.service.xxljob.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.ruoyi.business.domain.bo.DemotionResultBO;
import com.ruoyi.business.domain.bo.ProductDistributionResultBO;
import com.ruoyi.business.domain.koc.*;
import com.ruoyi.business.service.koc.*;
import com.ruoyi.business.service.xxljob.XXLJobHandlerService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.business.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class XXLJobHandlerServiceImpl implements XXLJobHandlerService {

    @Resource
    private ITbUserService tbUserService;

    @Resource
    private ITbUserKocTaskInfoService tbUserKocTaskInfoService;

    @Resource
    private ITbUserKocProductLogService tbUserKocProductLogService;

    @Resource
    private ITbKocLevelService tbKocLevelService;

    @Override
    public void downKocUserKocLevelHandler() {
        log.info("开始执行KOC用户降级处理");
        try {
            int pageSize = 50;
            Page<TbUser> page = new Page<>(1, pageSize);

            // 需要处理的KOC等级ID
            List<Long> queryKocLevelIds = Arrays.asList(
                UserKocLevelEnum.GH_KOC_1.getKocLevelId(),
                UserKocLevelEnum.PX_KOC_2.getKocLevelId(),
                UserKocLevelEnum.SQ_KOC_3.getKocLevelId()
            );
            // 批量查询等级配置信息
            Map<Long, TbKocLevel> kocLevelMap = batchQueryKocLevels(queryKocLevelIds);
            int totalProcessed = 0;
            int totalDemoted = 0;
            while (true) {
                Page<TbUser> pageRes = tbUserService.page(page,
                    Wrappers.lambdaQuery(TbUser.class)
                        .eq(TbUser::getStatus, 0)
                        .eq(TbUser::getIsKoc, Constants.TRUE_1)
                        .in(TbUser::getKocLevelId, queryKocLevelIds)
                        .orderByDesc(TbUser::getCreateTime));

                if (CollUtil.isEmpty(pageRes.getRecords())) {
                    log.info("没有更多KOC用户需要处理");
                    break;
                }
                log.info("开始处理第 {} 批用户，数量: {}", page.getCurrent(), pageRes.getRecords().size());
                DemotionResultBO result = processUserDemotionBatch(pageRes.getRecords(), kocLevelMap);
                totalProcessed += result.getProcessedCount();
                totalDemoted += result.getDemotedCount();

                log.info("第 {} 批用户处理完成，处理: {} 个用户，降级: {} 个用户",
                    page.getCurrent(), result.getProcessedCount(), result.getDemotedCount());

                if (!pageRes.hasNext()) {
                    break;
                }
                page.setCurrent(page.getCurrent() + 1);
            }

            log.info("KOC用户降级处理完成，总计处理用户: {} 个，降级用户: {} 个",
                totalProcessed, totalDemoted);

        } catch (Exception e) {
            log.error("KOC用户降级处理发生异常", e);
            throw new RuntimeException("用户降级处理失败", e);
        }
    }

    /**
     * 批量处理用户降级
     */
    @Transactional(rollbackFor = Exception.class)
    public DemotionResultBO processUserDemotionBatch(List<TbUser> users, Map<Long, TbKocLevel> kocLevelMap) {
        if (CollUtil.isEmpty(users)) {
            return new DemotionResultBO(0, 0);
        }

        List<Long> userIds = users.stream().map(TbUser::getId).collect(Collectors.toList());

        // 批量查询用户任务记录
        Map<Long, List<TbUserKocTaskInfo>> userTasksMap = batchQueryUserTasks(userIds, kocLevelMap);

        List<TbUser> usersToUpdate = new ArrayList<>();
        int demotedCount = 0;

        for (TbUser user : users) {
            try {
                TbKocLevel currentLevel = kocLevelMap.get(user.getKocLevelId());
                if (currentLevel == null) {
                    log.warn("用户 {} 的KOC等级配置不存在，等级ID: {}", user.getId(), user.getKocLevelId());
                    continue;
                }

                boolean shouldDemote = checkUserDemotion(user, currentLevel, userTasksMap.get(user.getId()));
                if (shouldDemote) {
                    TbUser updatedUser = createDemotedUser(user, currentLevel);
                    usersToUpdate.add(updatedUser);
                    demotedCount++;

                    log.info("用户降级处理，用户ID: {}, 原等级: {}, 新等级: {}",
                        user.getId(), currentLevel.getName(),
                        updatedUser.getKocLevelId() == null ? "非KOC" : updatedUser.getKocLevelName());
                }

            } catch (Exception e) {
                log.error("处理用户降级失败，用户ID: {}", user.getId(), e);
            }
        }

        // 批量更新用户
        if (CollUtil.isNotEmpty(usersToUpdate)) {
            tbUserService.updateBatchById(usersToUpdate);
        }

        return new DemotionResultBO(users.size(), demotedCount);
    }

    /**
     * 检查用户是否符合降级条件
     */
    private boolean checkUserDemotion(TbUser user, TbKocLevel currentLevel, List<TbUserKocTaskInfo> taskInfos) {
        // 检查成为KOC等级的时间是否满足降级检查条件
        if (user.getKocLevelTime() == null) {
            log.warn("用户 {} 的KOC等级时间为空，跳过处理", user.getId());
            return false;
        }

        LocalDate today = LocalDate.now();
        LocalDate monthsAgo = today.minusMonths(currentLevel.getDownKocTaskTypeHold());
        LocalDate kocLevelDate = user.getKocLevelTime().toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalDate();

        // 如果成为KOC等级的时间不足n个月，跳过处理
        if (kocLevelDate.isAfter(monthsAgo)) {
            log.debug("用户 {} 成为当前等级时间不足 {} 个月，跳过降级检查",
                user.getId(), currentLevel.getDownKocTaskTypeHold());
            return false;
        }

        // 获取需要检查的月份范围
        List<String> checkMonths = getCheckMonths(currentLevel.getDownKocTaskTypeHold());

        // 解析必做任务类型
        List<Long> mustTaskTypeIds = parseMustTaskTypes(currentLevel.getMustKocTaskType());
        if (CollUtil.isEmpty(mustTaskTypeIds)) {
            log.debug("用户 {} 的当前等级没有必做任务配置，跳过降级检查", user.getId());
            return false;
        }

        // 检查必做任务完成情况
        return checkMustTasksCompletion(mustTaskTypeIds, checkMonths, taskInfos);
    }

    /**
     * 检查必做任务完成情况
     */
    private boolean checkMustTasksCompletion(List<Long> mustTaskTypeIds, List<String> checkMonths,
                                             List<TbUserKocTaskInfo> taskInfos) {
        if (CollUtil.isEmpty(taskInfos)) {
            log.debug("用户在检查期内无任何任务记录，需要降级");
            return true;
        }

        // 按任务类型和月份分组，只统计审核通过的任务
        Map<Long, Set<String>> taskCompletionMap = taskInfos.stream()
            .filter(task -> TaskCheckStatusEnum.CHECK_PASS.getStatus().equals(task.getCheckStatus()))
            .collect(Collectors.groupingBy(
                TbUserKocTaskInfo::getKocTaskTypeId,
                Collectors.mapping(TbUserKocTaskInfo::getKocDate, Collectors.toSet())
            ));

        // 检查每个必做任务类型在检查期内是否有至少一条完成记录
        for (Long taskTypeId : mustTaskTypeIds) {
            Set<String> completedMonths = taskCompletionMap.get(taskTypeId);
            if (completedMonths == null || completedMonths.isEmpty()) {
                log.debug("必做任务类型 {} 在检查期内无任何完成记录", taskTypeId);
                return true;
            }

            // 检查该任务类型在检查期内是否有至少一个月有完成记录
            boolean hasCompletionInCheckPeriod = checkMonths.stream()
                .anyMatch(completedMonths::contains);

            if (!hasCompletionInCheckPeriod) {
                log.debug("必做任务类型 {} 在检查期内没有任何月份有完成记录", taskTypeId);
                return true;
            }
        }

        log.debug("用户所有必做任务在检查期内均有完成记录，无需降级");
        return false;
    }

    /**
     * 创建降级后的用户信息
     */
    private TbUser createDemotedUser(TbUser user, TbKocLevel currentLevel) {
        TbUser updatedUser = new TbUser();
        updatedUser.setId(user.getId());
        updatedUser.setKocLevelTime(new Date());

        // 根据当前等级确定降级目标
        if (Objects.equals(currentLevel.getId(), UserKocLevelEnum.SQ_KOC_3.getKocLevelId())) {
            // 3级降2级
            TbKocLevel targetLevel = tbKocLevelService.getById(UserKocLevelEnum.PX_KOC_2.getKocLevelId());
            updatedUser.setKocLevelId(targetLevel.getId());
            updatedUser.setKocLevelName(targetLevel.getName());
        } else if (Objects.equals(currentLevel.getId(), UserKocLevelEnum.PX_KOC_2.getKocLevelId())) {
            // 2级降1级
            TbKocLevel targetLevel = tbKocLevelService.getById(UserKocLevelEnum.GH_KOC_1.getKocLevelId());
            updatedUser.setKocLevelId(targetLevel.getId());
            updatedUser.setKocLevelName(targetLevel.getName());
        } else if (Objects.equals(currentLevel.getId(), UserKocLevelEnum.GH_KOC_1.getKocLevelId())) {
            // 1级降为非KOC用户
            updatedUser.setKocLevelId(null);
            updatedUser.setKocLevelName(null);
            updatedUser.setIsKoc(Constants.FALSE_0);
        }

        return updatedUser;
    }

    /**
     * 批量查询等级配置
     */
    private Map<Long, TbKocLevel> batchQueryKocLevels(List<Long> levelIds) {
        List<TbKocLevel> levels = tbKocLevelService.listByIds(levelIds);
        return levels.stream().collect(Collectors.toMap(TbKocLevel::getId, Function.identity()));
    }

    /**
     * 批量查询用户任务记录
     */
    private Map<Long, List<TbUserKocTaskInfo>> batchQueryUserTasks(List<Long> userIds, Map<Long, TbKocLevel> kocLevelMap) {
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }

        // 获取所有必做任务类型ID
        Set<Long> allMustTaskTypeIds = kocLevelMap.values().stream()
            .map(level -> parseMustTaskTypes(level.getMustKocTaskType()))
            .flatMap(List::stream)
            .collect(Collectors.toSet());

        if (CollUtil.isEmpty(allMustTaskTypeIds)) {
            return userIds.stream().collect(Collectors.toMap(Function.identity(), id -> new ArrayList<>()));
        }

        // 计算最大检查月份范围（取所有等级中最大的downKocTaskTypeHold）
        int maxCheckMonths = kocLevelMap.values().stream()
            .mapToInt(TbKocLevel::getDownKocTaskTypeHold)
            .max()
            .orElse(3); // 默认3个月

        LocalDate startDate = LocalDate.now().minusMonths(maxCheckMonths);
        String startMonth = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));

        // 批量查询任务记录
        List<TbUserKocTaskInfo> taskInfos = tbUserKocTaskInfoService.list(
            Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
                .in(TbUserKocTaskInfo::getUserId, userIds)
                .in(TbUserKocTaskInfo::getKocTaskTypeId, allMustTaskTypeIds)
                .eq(TbUserKocTaskInfo::getCheckStatus, TaskCheckStatusEnum.CHECK_PASS.getStatus())
                .ge(TbUserKocTaskInfo::getKocDate, startMonth));

        return taskInfos.stream()
            .collect(Collectors.groupingBy(TbUserKocTaskInfo::getUserId));
    }

    /**
     * 获取需要检查的月份列表
     */
    private List<String> getCheckMonths(int monthsToCheck) {
        LocalDate today = LocalDate.now();
        LocalDate startDate = today.minusMonths(monthsToCheck);
        LocalDate endDate = today.minusMonths(1);

        return Stream.iterate(startDate, date -> date.plusMonths(1))
            .limit(ChronoUnit.MONTHS.between(startDate, endDate) + 1)
            .map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM")))
            .collect(Collectors.toList());
    }

    /**
     * 解析必做任务类型
     */
    private List<Long> parseMustTaskTypes(String mustKocTaskType) {
        if (StringUtils.isEmpty(mustKocTaskType)) {
            return Collections.emptyList();
        }

        return Arrays.stream(mustKocTaskType.split(","))
            .map(String::trim)
            .filter(StringUtils::isNotEmpty)
            .map(Long::valueOf)
            .collect(Collectors.toList());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upKocUserKocLevelHandler() {
        // 本月 1号 查询 前三个月的 用户必做 与 升级必做任务 完成情况
        int pageNum = 1;
        int pageSize = 500;
        // 查询 koc 1 3 用户列表
        List<Long> queryKocLevelIds = new ArrayList<>();
        queryKocLevelIds.add(UserKocLevelEnum.GH_KOC_1.getKocLevelId());
        queryKocLevelIds.add(UserKocLevelEnum.PX_KOC_2.getKocLevelId());
        Page<TbUser> page = new Page<>(pageNum, pageSize);
        while (true) {
            Page<TbUser> pageRes = tbUserService.page(page, Wrappers.lambdaQuery(TbUser.class)
                .eq(TbUser::getStatus, 0)
                .eq(TbUser::getIsKoc, Constants.TRUE_1)
                .in(TbUser::getKocLevelId, queryKocLevelIds)
                .orderByDesc(TbUser::getCreateTime)
            );
            // 如果当前页没有记录了，结束循环
            if (CollUtil.isEmpty(pageRes.getRecords())) {
                break;
            }
            pageRes.getRecords().forEach(this::processUpLevelUserKocLevel);
            // 准备下一页
            page.setCurrent(page.getCurrent() + 1);
            pageNum++;
        }
    }

    @Override
    public void inChatGroupTaskSubmitHandler() {
        int pageNum = 1;
        int pageSize = 500;
        LocalDate today = LocalDate.now();
        YearMonth yearMonth = YearMonth.from(today);
        String yearMonthString = yearMonth.toString();

        while (true) {
            // 每次循环创建新的Page对象
            Page<TbUser> page = new Page<>(pageNum, pageSize);
            Page<TbUser> pageRes = tbUserService.page(page, Wrappers.lambdaQuery(TbUser.class)
                .eq(TbUser::getStatus, 0)
                .eq(TbUser::getIsKoc, Constants.TRUE_1)
                .eq(TbUser::getKocLevelId, UserKocLevelEnum.SQ_KOC_3.getKocLevelId())
                .orderByDesc(TbUser::getCreateTime)
            );

            List<TbUser> records = pageRes.getRecords();
            if (CollUtil.isEmpty(records)) {
                break;
            }
            // 批量查询已存在的任务，避免N+1查询
            List<Long> userIds = records.stream().map(TbUser::getId).collect(Collectors.toList());

            List<TbUserKocTaskInfo> existingTasks = tbUserKocTaskInfoService.list(
                Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
                    .eq(TbUserKocTaskInfo::getKocDate, yearMonthString)
                    .eq(TbUserKocTaskInfo::getKocTaskId, KocTaskEnum.NBQFY.getKocTaskId())
                    .in(TbUserKocTaskInfo::getUserId, userIds)
            );

            Set<Long> existingUserIds = existingTasks.stream()
                .map(TbUserKocTaskInfo::getUserId)
                .collect(Collectors.toSet());

            List<TbUserKocTaskInfo> taskList = new ArrayList<>();
            for (TbUser user : records) {
                if (!existingUserIds.contains(user.getId())) {
                    TbUserKocTaskInfo task = createTaskInfo(user, yearMonthString);
                    taskList.add(task);
                }
            }

            if (CollUtil.isNotEmpty(taskList)) {
                tbUserKocTaskInfoService.saveBatch(taskList);
            }

            // 检查是否还有下一页
            if (pageNum >= pageRes.getPages()) {
                break;
            }
            pageNum++;
        }
    }

    private TbUserKocTaskInfo createTaskInfo(TbUser user, String yearMonthString) {
        TbUserKocTaskInfo task = new TbUserKocTaskInfo();
        task.setId(IdWorker.getId());
        task.setKocTaskTypeId(KocTaskTypeEnum.NQHY_WH.getKocTaskTypeId());
        task.setKocTaskTypeCode(KocTaskTypeEnum.NQHY_WH.getCode());
        task.setKocTaskTypeName(KocTaskTypeEnum.NQHY_WH.getName());
        task.setKocTaskId(KocTaskEnum.NBQFY.getKocTaskId());
        task.setKocTaskName(KocTaskEnum.NBQFY.getName());
        task.setUserId(user.getId());
        task.setUserPhone(user.getMobile());
        task.setUserRealName(user.getRealName());
        task.setUserNickname(user.getNickname());
        task.setUserKocLevelId(user.getKocLevelId());
        task.setUserKocLevelName(user.getKocLevelName());
        task.setKocDate(yearMonthString);
        task.setCheckStatus(TaskCheckStatusEnum.ORIGINAL.getStatus());
        return task;
    }

    /**
     * 处理单个用户的KOC 升级
     */
    private void processUpLevelUserKocLevel(TbUser user) {
        // 只有 1 3 能升级 koc level id 为 1 和 3 的能升级 即 官号koc1级 与 品宣koc2级 小红书2级与 社群3级不计入计算
        TbKocLevel tbKocLevel = tbKocLevelService.getById(user.getKocLevelId());
        LocalDate today = LocalDate.now();
        LocalDate monthsAgo = today.minusMonths(tbKocLevel.getUpRequestKocTaskTypeHold());
        if (user.getKocLevelTime() == null) {
            log.warn("用户 {} 的KOC等级时间为空，跳过处理", user.getId());
            return;
        }
        // 将Date转换为LocalDate
        LocalDate kocLevelDate = user.getKocLevelTime().toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalDate();
        // 如果成为KOC等级的时间不足n个月，跳过处理
        if (kocLevelDate.isAfter(monthsAgo)) {
            return;
        }
        LocalDate upStartDate = today.minusMonths(tbKocLevel.getUpRequestKocTaskTypeHold());
        // 截止到上个月
        LocalDate upEndDate = today.minusMonths(1);
        List<String> upKocDateList = Stream.iterate(upStartDate, date -> date.plusMonths(1))
            .limit(ChronoUnit.MONTHS.between(upStartDate, upEndDate) + 1)
            .map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM")))
            .collect(Collectors.toList());
        // 必做任务类型 集合
        String mustKocTaskType = tbKocLevel.getMustKocTaskType();
        List<Long> mustKocTaskTypeIds = StringUtils.isNotEmpty(mustKocTaskType)
            ? Arrays.stream(mustKocTaskType.split(","))
            .map(String::trim)
            .filter(StringUtils::isNotEmpty)
            .map(Long::valueOf)
            .collect(Collectors.toList())
            : Collections.emptyList();

        // 升级必做任务类型
        String upKocTaskType = tbKocLevel.getUpRequestKocTaskType();
        List<Long> upLevelKocTaskTypeIds = StringUtils.isNotEmpty(upKocTaskType)
            ? Arrays.stream(upKocTaskType.split(","))
            .map(String::trim)
            .filter(StringUtils::isNotEmpty)
            .map(Long::valueOf)
            .collect(Collectors.toList())
            : Collections.emptyList();
        Map<String, Map<Long, Map<Long, List<TbUserKocTaskInfo>>>> mustKocTaskMap = Maps.newHashMap();
        Map<String, Map<Long, Map<Long, List<TbUserKocTaskInfo>>>> upLevelKocTaskMap = Maps.newHashMap();
        if (CollUtil.isNotEmpty(mustKocTaskTypeIds)) {
            // 查询当前用户 当前koc 等级 必做的任务类型列表
            List<TbUserKocTaskInfo> list = tbUserKocTaskInfoService.list(Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
                .in(TbUserKocTaskInfo::getKocTaskTypeId, mustKocTaskTypeIds)
                .in(TbUserKocTaskInfo::getKocDate, upKocDateList)
                .in(TbUserKocTaskInfo::getUserId, user.getId()));
            mustKocTaskMap = Optional.ofNullable(list)
                .orElse(Collections.emptyList())
                .stream()
                .collect(Collectors.groupingBy(
                    task -> task.getKocDate() != null ? task.getKocDate() : "未知日期",
                    Collectors.groupingBy(
                        task -> task.getKocTaskTypeId() != null ? task.getKocTaskTypeId() : 0L,
                        Collectors.groupingBy(
                            task -> task.getKocTaskId() != null ? task.getKocTaskId() : 0L
                        )
                    )
                ));
        }
        if (CollUtil.isNotEmpty(upLevelKocTaskTypeIds)) {
            // 查询当前koc 等级 升级任务完成情况
            List<TbUserKocTaskInfo> list = tbUserKocTaskInfoService.list(Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
                .in(TbUserKocTaskInfo::getKocTaskTypeId, upLevelKocTaskTypeIds)
                .in(TbUserKocTaskInfo::getKocDate, upKocDateList)
                .in(TbUserKocTaskInfo::getUserId, user.getId()));
            upLevelKocTaskMap = Optional.ofNullable(list)
                .orElse(Collections.emptyList())
                .stream()
                .collect(Collectors.groupingBy(
                    task -> task.getKocDate() != null ? task.getKocDate() : "未知日期",
                    Collectors.groupingBy(
                        task -> task.getKocTaskTypeId() != null ? task.getKocTaskTypeId() : 0L,
                        Collectors.groupingBy(
                            task -> task.getKocTaskId() != null ? task.getKocTaskId() : 0L
                        )
                    )
                ));
        }
        // 必做任务 flag
        AtomicBoolean mustFlag = new AtomicBoolean(true);
        // 升级任务 flag
        AtomicBoolean upFlag = new AtomicBoolean(true);
        if (CollUtil.isNotEmpty(upLevelKocTaskTypeIds)) {
            if (CollUtil.isEmpty(upLevelKocTaskMap)) {
                upFlag.set(false);
            } else {
                for (String kocDate : upKocDateList) {
                    if (upLevelKocTaskMap.containsKey(kocDate)) {
                        Map<Long, Map<Long, List<TbUserKocTaskInfo>>> longMapMap = upLevelKocTaskMap.get(kocDate);
                        for (Long taskTypeId : upLevelKocTaskTypeIds) {
                            if (!longMapMap.containsKey(taskTypeId)) {
                                upFlag.set(false);
                                break;
                            }
                        }
                    } else {
                        upFlag.set(false);
                        break;
                    }
                }
            }
        }
        // koc 等级必做任务
        Map<String, Map<Long, Map<Long, List<TbUserKocTaskInfo>>>> finalMustKocTaskMap = mustKocTaskMap;
        for (String kocDate : upKocDateList) {
            if (finalMustKocTaskMap.containsKey(kocDate)) {
                Map<Long, Map<Long, List<TbUserKocTaskInfo>>> longMapMap = finalMustKocTaskMap.get(kocDate);
                for (Long taskTypeId : mustKocTaskTypeIds) {
                    if (longMapMap.containsKey(taskTypeId)) {
                        if (mustKocTaskTypeIds.contains(KocTaskTypeEnum.GHHD.getKocTaskTypeId())) {
                            if (Objects.equals(taskTypeId, KocTaskTypeEnum.GHHD.getKocTaskTypeId())) {
                                Map<Long, List<TbUserKocTaskInfo>> longListMap = longMapMap.get(taskTypeId);
                                if (longListMap.size() <= 1) {
                                    mustFlag.set(false);
                                    break;
                                }
                            }
                        }
                    } else {
                        mustFlag.set(false);
                        break;
                    }
                }

            } else {
                mustFlag.set(false);
                break;
            }

        }

        if (mustFlag.get() && upFlag.get()) {
            if (Objects.equals(tbKocLevel.getId(), UserKocLevelEnum.GH_KOC_1.getKocLevelId())) {
                // 1 级 升 2 级
                TbKocLevel kocLevel2 = tbKocLevelService.getById(UserKocLevelEnum.PX_KOC_2.getKocLevelId());
                user.setKocLevelId(kocLevel2.getId());
                user.setKocLevelName(kocLevel2.getName());
                user.setKocLevelTime(new Date());
                tbUserService.updateById(user);
            }
            if (Objects.equals(tbKocLevel.getId(), UserKocLevelEnum.PX_KOC_2.getKocLevelId())) {
                // 2级升 3级
                TbKocLevel kocLevel3 = tbKocLevelService.getById(UserKocLevelEnum.SQ_KOC_3.getKocLevelId());
                user.setKocLevelId(kocLevel3.getId());
                user.setKocLevelName(kocLevel3.getName());
                user.setKocLevelTime(new Date());
                tbUserService.updateById(user);
            }
        }
    }


}
